package com.finger.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.finger.commonutil.exception.YyghException;
import com.finger.modelservice.enums.OrderStatusEnum;
import com.finger.modelservice.enums.PaymentTypeEnum;
import com.finger.modelservice.enums.RefundStatusEnum;
import com.finger.modelservice.model.order.OrderInfo;
import com.finger.modelservice.model.order.PaymentInfo;
import com.finger.modelservice.model.order.RefundInfo;
import com.finger.modelservice.result.ResultCodeEnum;
import com.finger.modelservice.vo.msm.MsmVo;
import com.finger.modelservice.vo.order.OrderMqVo;
import com.finger.modelservice.vo.order.SignInfoVo;
import com.finger.orderservice.client.HospClient;
import com.finger.orderservice.service.OrderInfoService;
import com.finger.orderservice.service.PaymentInfoService;
import com.finger.orderservice.service.RefundInfoService;
import com.finger.orderservice.service.WeixinPayService;
import com.finger.orderservice.util.ConstantPropertiesUtil;
import com.finger.orderservice.util.HttpClient;
import com.finger.serviceutil.helper.HttpRequestHelper;
import com.finger.serviceutil.util.MD5;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.log4j.Log4j2;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Log4j2
@Service
public class WeixinPayServiceImpl implements WeixinPayService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    @Autowired
    private HospClient hospClient;

    @Override
    public Map<String, Object> createNative(String orderId) {

        try {

            Map redisMap = (Map) redisTemplate.opsForValue().get(orderId);

            if (redisMap != null) return redisMap;

            // 查询订单
            OrderInfo order = orderInfoService.getById(orderId);

            // 保存支付记录
            paymentInfoService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());

            //1、设置参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtil.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtil.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            DateTime dateTime = new DateTime(order.getReserveDate());
            String reserveDate = dateTime.toString("yyyy-MM-dd");
            String body = reserveDate + "就诊" + order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue() + "");
//            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtil.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            if (!StringUtils.isEmpty(resultMap.get("result_code"))) {
                redisTemplate.opsForValue().set(orderId, map, 15, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FAIL);
        }
    }

    @Override
    public Map queryPayStatus(String orderId) {

        try {
            // 1，根据订单id查询订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);

            // 2，封装提交参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtil.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtil.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            // 3，设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtil.PARTNERKEY));
            client.setHttps(true);
            client.post();
            // 4，得到微信接口返回的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            log.info("resultMap: " + resultMap);
            // 5，把接口数据返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public boolean reFund(String orderId) {

        try {
            PaymentInfo paymentInfo =
                    paymentInfoService.getOne(new QueryWrapper<PaymentInfo>().eq("order_id", orderId).eq("payment_type", PaymentTypeEnum.WEIXIN.getStatus()));

            if (paymentInfo == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);

            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);

            if (Objects.equals(refundInfo.getRefundStatus(), RefundStatusEnum.REFUND.getStatus())) return true;

            Map<String, String> paramMap = new HashMap<>(8);
            paramMap.put("appid", ConstantPropertiesUtil.APPID);       //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtil.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo());
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo());

            // 款单号
            paramMap.put("total_fee", paymentInfo.getTotalAmount().multiply(new BigDecimal("100")).longValue() + "");
            paramMap.put("refund_fee", paymentInfo.getTotalAmount().multiply(new BigDecimal("100")).longValue() + "");
//            paramMap.put("total_fee","1");
//            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtil.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtil.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean cancelOrder(String orderId) {


        // 根据订单查找订单记录
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        // 如果订单为空，抛出参数错误
        if (orderInfo == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        // 根据退号时间创建一个DateTime工具类
        DateTime dateTime = new DateTime(orderInfo.getQuitTime());
        // 如果退号时间已经过去，抛出异常
        if (dateTime.isBeforeNow()) throw new YyghException("取消订单时间已过，无法取消预约", 225);
        // 从医院设置模块远程调用查找医院设置信息
        SignInfoVo signInfoVO = hospClient.findSignInfoVO(orderInfo.getHoscode());
        // 如果没有查到医院设置信息，抛出异常
        if (signInfoVO == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        // 创建远程医院接口需要的参数并设置
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = MD5.encrypt(signInfoVO.getSignKey());
        reqMap.put("sign", sign);
        // 获取远程更新订单记录的返回结果
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVO.getApiUrl() + "/order/updateCancelStatus");
        // 如果成功码不为200，说明更新失败，抛出异常
        if (result.getIntValue("code") != 200) {
            throw new YyghException(result.getString("message"), 201);
        } else {
            // 判断订单支付状态是否为已支付
            if (Objects.equals(orderInfo.getOrderStatus(), OrderStatusEnum.PAID.getStatus())) {
                // 退款是否成功
                boolean isRefund = this.reFund(orderInfo.getId());
                if (!isRefund) {
                    return false;
                }
            }
            // 更新订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            orderInfoService.updateById(orderInfo);
            // 更新医院模块内的排班可预约数量
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            hospClient.updateSchedule(orderMqVo);
            return true;
        }

    }
}
